package com.gitee.neuray.security.generator.generatormd.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gitee.neuray.security.common.exception.BaseException;
import com.gitee.neuray.security.common.msg.ListRestResponse;
import com.gitee.neuray.security.common.msg.ObjectRestResponse;
import com.gitee.neuray.security.generator.enums.GenerateBizParmsEnum;
import com.gitee.neuray.security.generator.enums.GenerationTypeEnum;
import com.gitee.neuray.security.generator.generatormd.dto.GenColumnsBaseDto;
import com.gitee.neuray.security.generator.generatormd.dto.MultiTableDto;
import com.gitee.neuray.security.generator.generatormd.dto.SingleTableDto;
import com.gitee.neuray.security.generator.generatormd.vo.ViewCloumnsVO;
import org.apache.commons.io.IOUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import com.gitee.neuray.security.common.rest.BaseController;

import com.gitee.neuray.security.generator.generatormd.entity.TGenerateInfoEntity;
import com.gitee.neuray.security.generator.generatormd.biz.TGenerateInfoBiz;

import javax.servlet.http.HttpServletResponse;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;


/**
 * 代码生成器-代码生成信息
 *
 * @author zhhongyu
 * @email ${email}
 * @date 2020-01-09 10:45:47
 */
@RestController
@RequestMapping("generatormd")
public class TGenerateInfoController extends BaseController<TGenerateInfoBiz, TGenerateInfoEntity>{
    /**
     * 根据sql和指定的数据源生成指定的表结构
     * @param params
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/tableInfo",method = RequestMethod.POST)
    @ResponseBody
    public ListRestResponse<List<ViewCloumnsVO>> getTableViewInfo(@RequestBody Map params) throws Exception {
        List<Map<String,String>> tableViewInfo = baseBiz.getTableViewInfo(params);
        List<ViewCloumnsVO> viewCloumnsVOS = JSONArray.parseArray(JSONObject.toJSONString(tableViewInfo), ViewCloumnsVO.class);
        return new ListRestResponse<List<ViewCloumnsVO>>("",viewCloumnsVOS.size(),viewCloumnsVOS);
    }

    /**
     * 查询指定数据库中的所有的表信息
     * @param id
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/tables/{id}",method = RequestMethod.GET)
    @ResponseBody
    public ListRestResponse<List<Map>> getTables(@PathVariable String id)throws Exception{
        List<Map> tables = baseBiz.getTables(id);
        return new ListRestResponse<>("",tables.size(),tables);
    }

    /**
     * 根据标明获取详细信息
     * @param id 数据源id
     * @param tableName 表名称
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/tableInfo/{id}",method = RequestMethod.GET)
    public ListRestResponse<List<ViewCloumnsVO>> getTableInfo(@PathVariable String id,
                                                              @RequestParam String tableName)throws Exception{
        if(StringUtils.isEmpty(tableName)){
            throw new BaseException("表明不能为空或null..");
        }
        List<Map> tableInfo = baseBiz.getTableInfo(id, tableName);
        List<ViewCloumnsVO> viewCloumnsVOS = JSONArray.parseArray(JSONObject.toJSONString(tableInfo), ViewCloumnsVO.class);
        return new ListRestResponse<List<ViewCloumnsVO>>("",viewCloumnsVOS.size(),viewCloumnsVOS);
    }

    /**
     * 开始生成代码
     * @return
     */
    @RequestMapping(value="start",method = RequestMethod.POST)
    public void generator(@RequestBody Map map, HttpServletResponse response)throws Exception{
        String  type = (String) map.get(GenerateBizParmsEnum.generationType.name());
        if(StringUtils.isEmpty(type)){
            throw new BaseException("生成代码类型不能为空...");
        }
        byte[] data = null;
        GenerationTypeEnum typeEnum = GenerationTypeEnum.getEnum(type);
        if(typeEnum == null){
            throw new BaseException("生成代码的类型不对...");
        }
        LinkedHashMap hashMap = (LinkedHashMap) map.get("table");
        //单表生成代码
        if(GenerationTypeEnum.one.getValue().equals(type)){
            SingleTableDto singleTableDto = JSONObject.parseObject(JSONObject.toJSONString(map),SingleTableDto.class);
            singleTableDto.setTable(getGenColumnsDto(hashMap));
            singleTableDto.setAuthor(URLDecoder.decode(request.getHeader("name"),"utf-8"));
            data = baseBiz.singleGenerator(singleTableDto);
        }
        //多表生成代码
        if(GenerationTypeEnum.multi.getValue().equals(type)){
            MultiTableDto table = JSONObject.parseObject(JSONObject.toJSONString(map),MultiTableDto.class);
            table.setTable(getGenColumnsDto(hashMap));
            table.setAuthor(URLDecoder.decode(request.getHeader("name"),"utf-8"));
            data = baseBiz.multGenerator(table);
        }
        response.reset();
        String module = map.get("module")+".zip";
        response.setHeader("Content-Disposition", "attachment; filename="+module);
        response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/octet-stream; charset=UTF-8");

        IOUtils.write(data, response.getOutputStream());
    }

    private List<GenColumnsBaseDto> getGenColumnsDto(LinkedHashMap hashMap){
        List<GenColumnsBaseDto> list = new ArrayList<>();
        hashMap.forEach((key,val) ->{
            GenColumnsBaseDto columnBaseDto = JSONObject.parseObject(JSONObject.toJSONString(val), GenColumnsBaseDto.class);
            list.add(columnBaseDto);
        });
        return list;
    }
}
